
const { User, JoinClub, Club } = require("../db");
const axios = require('axios');
const jwt = require('jsonwebtoken');
const { secretKey } = require('../config/config');
const { Op } = require('sequelize');

const APPID = 'wx77204d8ffe2ce983';
const SECRET = 'd0f8b5928c62d5d6fbd3a1844d350a97';
async function getOpenId(code) {
    const response = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
        params: {
            appid: APPID,
            secret: SECRET,
            js_code: code,
            grant_type: 'authorization_code'
        }
    });
    return response.data;
}

exports.loginWX = async (req, res) => {
    const { code } = req.body;
    if (code) {
        try {
            const { openid } = await getOpenId(code);
            const tempUser = await User.findOne({ where: { openId: openid } });
            if (!tempUser) {
                // 如果不存在该用户，则随机新建
                const userinfo = await User.create({
                    openId: openid, username: '微信用户' + Math.floor(Math.random() * 1000000),
                    password: '123456', avatarUrl: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png',
                    postNums: 0, role: 'user'
                });
                const tokenStr = jwt.sign({ id: userinfo.dataValues.id, role: userinfo.role }, secretKey, { expiresIn: '11130s' })
                res.send({
                    status: 200,
                    message: '创建用户成功，登录成功！',
                    token: tokenStr, // 要发送给客户端的 token 字符串
                    user: {
                        ...tempUser.dataValues,
                        password: undefined     //抹除密码字段
                    },
                    isAnyClubTeacher: false,
                    club: [],
                    new: true
                })
            }
            else {
                // const clubInfs = await JoinClub.findAll({ where: { userId: tempUser.dataValues.id }, attributes: ['clubId'] })
                // const clubIds = clubInfs.map(club => club.clubId)

                const clubInfs = await User.findOne({
                    where: { id: tempUser.dataValues.id },
                    include: Club
                });
                const clubInfsRes = clubInfs.dataValues.Clubs.map(item => ({
                    ...item.dataValues,
                    role: item.dataValues.JoinClub.role,
                    joinStatus: item.dataValues.JoinClub.statu,
                    JoinClub: undefined
                }));
                // 如果clubInfsRes中存在role为club_teacher的记录   则isAnyClubTeacher为true
                const isAnyClubTeacher = clubInfsRes.some(item => item.role === 'club_teacher');

                const tokenStr = jwt.sign({ id: tempUser.dataValues.id, role: tempUser.dataValues.role }, secretKey, { expiresIn: '11130s' })

                res.send({
                    status: 200,
                    message: '登录成功！',
                    token: tokenStr, // 要发送给客户端的 token 字符串
                    user: {
                        ...tempUser.dataValues,
                        password: undefined     //抹除密码字段
                    },
                    club: clubInfsRes,
                    isAnyClubTeacher,
                    new: false
                })
            }
        } catch (error) {
            console.error(error);
            res.status(500).send('Failed to get openid');
        }
    } else {
        res.status(400).send('No code provided');
    }
};

exports.getUserInfo = async (req, res) => {
    console.log(req.user.id);
    const tempUser = await User.findOne({ where: { id: req.user.id } });
    if (tempUser) {
        res.send({
            status: 200,
            message: '获取用户信息成功！',
            user: {
                ...tempUser.dataValues,
                password: undefined     // 抹除密码字段
            }
        })
    }
}

// 修改用户信息接口
exports.updateUserInfo = async (req, res) => {
    const { id } = req.user
    const { username, avatarUrl } = req.body;
    const tempUser = await User.findOne({ where: { id: id } });
    if (tempUser) {
        const newInfo = await User.update({ username: username || tempUser.dataValues.username, avatarUrl: avatarUrl || tempUser.dataValues.avatarUrl }, { where: { id: id } });

        if (newInfo[0] === 1)
            res.send({
                status: 200,
                message: '修改用户信息成功！',
            })
        else {
            res.send({
                status: 500,
                message: '修改用户信息失败！',
            })
        }
    }
}


exports.login = async (req, res) => {
    const { username, password } = req.body

    if (username && password) {
        try {
            const tempUser = await User.findOne({ where: { username: username } });
            if (tempUser) {
                if (tempUser.dataValues.password === password) {
                    const tokenStr = jwt.sign({ id: tempUser.dataValues.id }, secretKey, { expiresIn: '11130s' })
                    const clubInfs = await User.findOne({
                        where: { id: tempUser.dataValues.id },
                        include: Club
                    });
                    const clubIndsRes=clubInfs.dataValues.Clubs.map(item=>({
                        ...item.dataValues,
                        role: item.dataValues.JoinClub.role,
                        joinStatus: item.dataValues.JoinClub.statu,
                        JoinClub: undefined,
                    }))
                    const inAnyClubTeacher=clubIndsRes.some(item=>item.role==='club_teacher')
                    res.send({
                        status: 200,
                        message: '登录成功！',
                        user: {...tempUser.dataValues,inAnyClubTeacher},
                        token: tokenStr,
                        club:clubIndsRes,
                    })
                }
                else {
                    res.send({
                        status: 401,
                        message: '密码错误！'
                    })
                }
            }
            else {
                res.send({
                    status: 404,
                    message: '用户不存在！'
                })
            }
        }
        catch (err) {
            console.log(err);
            res.status(500).send('Failed to login');
        }
    }
}

//新建账户
exports.register = async (req, res) => {
    const { username, password } = req.body
    if (username && password) {
        try {
            const tempUser = await User.findOne({ where: { username: username } });
            if (tempUser) {
                res.send({
                    status: 401,
                    message: '用户已存在！'
                })
            } else {
                const newUser = await User.create({
                    openId: "bcAccount", username: username,
                    password: password, avatarUrl: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png',
                    postNums: 0
                });
                if (newUser) {
                    res.send({
                        status: 200,
                        message: '注册成功！',
                    })
                } else {
                    res.send({
                        status: 500,
                        message: '注册失败！',
                    })
                }
            }
        } catch (err) {
            console.log(err);
            res.status(500).send('Failed to register');
        }
    }
}

// 修改用户权限
exports.editUserRole = async (req, res) => {
    const { id, role } = req.body
    const { id: userId } = req.user
    const userInf = await User.findOne({ where: { id: userId } })
    if (userInf.dataValues.role === 'jyu_admin') {
        if (id && role) {
            try {
                const tempUser = await User.findOne({ where: { id: id } });
                if (tempUser) {
                    await User.update({ role: role }, { where: { id: id } });
                    res.send({
                        status: 200,
                        message: '修改成功！',
                    })
                } else {
                    res.send({
                        status: 404,
                        message: '用户不存在！'
                    })
                }
            } catch (err) {
                console.log(err);
                res.status(500).send('Failed to edit user role');
            }
        }
    }
    else {
        res.send({
            status: 401,
            message: '权限不足！'
        })
    }
}

//获得所有用户信息
exports.getAllUsers = async (req, res) => {
    const { id: userId } = req.user
    const { pageNum, pageSize, username } = req.query
    const userInf = await User.findOne({ where: { id: userId } })
    if (userInf.dataValues.role === 'jyu_admin') {
        try {
            const users = await User.findAll({
                offset: (+pageNum - 1) * +pageSize,
                limit: +pageSize,
                where: {
                    username: {
                        [Op.like]: `%${username}%`
                    }
                }
            });
            const resTotal = await User.count();
            res.send({
                status: 200,
                message: '获取成功！',
                data: users,
                total: resTotal
            })
        }
        catch (err) {
            console.log(err);
            res.status(500).send('Failed to get all users');
        }
    }
}